package iamdev.me.ytds.service.impl;


import iamdev.me.ytds.service.IEsSqlService;
import jodd.http.HttpRequest;
import jodd.http.HttpResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;


/**
 * Title: EsSqlService.java
 *
 * @author zxc
 * @time 2018/4/20 18:02
 */

@Service
@Configuration
public class EsSqlService implements IEsSqlService {
    private String esURL;
    @Override
    public String sql(String sql){
        try {
            sql = URLEncoder.encode(sql,"utf-8");
            HttpRequest request = HttpRequest.get(esURL+"/_sql?sql="+sql);
            request.timeout(5000);
            HttpResponse response = request.send();
            String result = new String(response.bodyBytes(), "utf-8");
            return result;
        }catch (UnsupportedEncodingException e){
        }
        return null;
    }
    @Override
    public String explainSql(String sql){
        try {
            sql = URLEncoder.encode(sql,"utf-8");
            HttpRequest request = HttpRequest.get(esURL+"/_sql/_explain?sql="+sql);
            request.timeout(5000);
            HttpResponse response = request.send();
            String result = new String(response.bodyBytes(), "utf-8");
            return result;
        }catch (UnsupportedEncodingException e){
        }
        return null;
    }
}
